package com.jz.community.modulemine.money.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.jakewharton.rxbinding2.view.RxView;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.enums.CodeType;
import com.jz.community.basecomm.utils.OperationTool;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.RxTool;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.money.bean.MoneyActiveBean;
import com.jz.community.modulemine.money.bean.MoneyRechargeBean;
import com.jz.community.modulemine.money.presenter.MoneyRechargePresenter;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.shequren.communityPeople.pay.bean.PayEvent;
import cn.shequren.communityPeople.pay.constants.CommUnityPayConstants;
import cn.shequren.communityPeople.pay.utils.CommUnityPayUtil;
import io.reactivex.Observable;

public class MoneyRechargeActivity extends BaseMvpActivity<MoneyRechargeView.View, MoneyRechargePresenter> implements MoneyRechargeView.View {

    @BindView(R2.id.recharge_back)
    ImageView rechargeBack;
    @BindView(R2.id.recharge_title)
    TextView rechargeTitle;
    @BindView(R2.id.recharge_toolbar)
    Toolbar rechargeToolbar;
    @BindView(R2.id.recharge_tips_content)
    TextView rechargeTipsContent;
    @BindView(R2.id.recharge_tips_rl)
    RelativeLayout rechargeTipsRl;
    @BindView(R2.id.recharge_r)
    TextView rechargeR;
    @BindView(R2.id.recharge_edit)
    EditText rechargeEdit;
    @BindView(R2.id.recharge_edit_delete)
    ImageView rechargeEditDelete;
    @BindView(R2.id.recharge_money)
    TextView rechargeMoney;
    @BindView(R2.id.recharge_active)
    TextView rechargeActive;
    @BindView(R2.id.recharge_wechat_icon)
    ImageView rechargeWechatIcon;
    @BindView(R2.id.recharge_wechat_choose)
    ImageView rechargeWechatChoose;
    @BindView(R2.id.recharge_wechat_rl)
    RelativeLayout rechargeWechatRl;
    @BindView(R2.id.recharge_alpay_icon)
    ImageView rechargeAlpayIcon;
    @BindView(R2.id.recharge_alipay_choose)
    ImageView rechargeAlipayChoose;
    @BindView(R2.id.recharge_alipay_rl)
    RelativeLayout rechargeAlipayRl;
    @BindView(R2.id.recharge_enter)
    TextView rechargeEnter;
    @BindView(R2.id.recharge_parent_ll)
    LinearLayout rechargeParentLl;

    //我的余额
    private double myMoney = 0;
    private String strMyMoney = "";

    //活动基础金额
    private double baseMoney = 0;
    //活动赠送
    private double activeMoney = 0;

    private String sContent = "";
    private int isGift = 0;//是否有活动 0 没有 1有
    private int rechargeType = 0; // 1 微信 2支付宝

    private final static String PAY_WECHAT = "MicroMessenger";
    private final static String PAY_ALIPAY = "Alipay";

    private Observable<PayEvent> toPayRxBusObser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_money_recharge;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected MoneyRechargePresenter createPresenter() {
        return new MoneyRechargePresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this)
                .titleBar(rechargeToolbar)
                .statusBarDarkFont(true, 0.2f)//当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
                .init();

        rechargeTitle.setText("E卡充值");

        strMyMoney = getIntent().getStringExtra("myMoney");
        myMoney = RxDataTool.stringToDouble(strMyMoney);

    }

    @SuppressLint("CheckResult")
    @Override
    protected void initDatas() {
        super.initDatas();
        rechargeMoney.setText(myMoney + "");
        //使rechargeEdit只能小数点后输入两位小数
        RxTool.setEdTwoDecimalAndMax(rechargeEdit, 11);

        rechargeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    rechargeEditDelete.setVisibility(View.VISIBLE);

                    double editMoney = RxDataTool.stringToDouble(s.toString());
                    double totalMoney = OperationTool.add(myMoney, editMoney);

                    //格式化设置，防止系统自动转化为科学计数法
                    DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
                    String totalString = decimalFormat.format(totalMoney);

                    rechargeMoney.setText(totalString);

                    if (isGift == 1) {
                        //有活动
                        if (baseMoney != 0 && activeMoney != 0) {
                            if (editMoney >= baseMoney) {
                                rechargeActive.setVisibility(View.VISIBLE);
                                int multiple = OperationTool.divInt(editMoney, baseMoney);

                                String activeString = decimalFormat.format(activeMoney * multiple);
                                rechargeActive.setText("+¥" + activeString);
                            } else {
                                rechargeActive.setVisibility(View.GONE);
                            }
                        }
                    }

                    if (rechargeType != 0) {
                        //已选择支付方式
                        String str = s.toString().trim();
                        String last = str.substring(str.length() - 1);

                        if (editMoney > 0) {
                            if (!last.equals(".")) {
                                rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_red);
                                rechargeEnter.setEnabled(true);
                            } else {
                                //如果最后一位为"." 则不能提交
                                rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_gray);
                                rechargeEnter.setEnabled(false);
                            }

                        } else {
                            rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_gray);
                            rechargeEnter.setEnabled(false);
                        }

                    } else {
                        //未选择支付方式
                        rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_gray);
                        rechargeEnter.setEnabled(false);
                    }

                } else {
                    rechargeMoney.setText(myMoney + "");

                    rechargeActive.setVisibility(View.GONE);

                    rechargeEditDelete.setVisibility(View.GONE);
                    rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_gray);
                    rechargeEnter.setEnabled(false);
                }


            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        RxView.clicks(rechargeEnter)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    if (rechargeType != 0) {
                        sContent = rechargeEdit.getText().toString().trim();
                        if (!RxDataTool.isNullString(sContent)) {
                            //输入内容不为空
                            String last = sContent.substring(sContent.length() - 1);
                            if (!last.equals(".")) {
                                //最后一位不是.
                                double rechargeMoney = RxDataTool.stringToDouble(sContent);
                                if (rechargeMoney > 0) {
                                    //金额大于0
                                    if (rechargeType == 1) {
                                        //微信支付
                                        mPresenter.rechargeMoney(PAY_WECHAT, rechargeMoney);
                                    } else if (rechargeType == 2) {
                                        //支付宝支付
                                        mPresenter.rechargeMoney(PAY_ALIPAY, rechargeMoney);
                                    }

                                }
                            }

                        }
                    }


                });

        mPresenter.initMoneyActive();
        paymentCallback();
    }

    @Override
    public void setActiveData(MoneyActiveBean entity) {
        //是否开启(开启:0,不开启:1)
        if (entity.getIsOpen() == 0) {
            //活动开启
            if (!RxDataTool.isNullString(entity.getOfferPrice())) {
                isGift = 1;
                rechargeTipsRl.setVisibility(View.VISIBLE);
                rechargeTipsContent.setText(entity.getName());

                activeMoney = RxDataTool.stringToDouble(entity.getOfferPrice());
                if (!RxDataTool.isNullString(entity.getPrice())) {
                    baseMoney = RxDataTool.stringToDouble(entity.getPrice());
                } else {
                    rechargeActive.setVisibility(View.GONE);
                }

            } else {
                rechargeActive.setVisibility(View.GONE);
            }

        } else {
            //活动关闭
            isGift = 0;
            rechargeTipsRl.setVisibility(View.GONE);
            rechargeActive.setVisibility(View.GONE);
        }

    }

    @Override
    public void rechargeSuccess(MoneyRechargeBean entity) {
        if (!RxDataTool.isNullString(entity.getData())) {
            if (rechargeType == 1) {
                //微信充值
                CommUnityPayUtil.goPay(mActivity, CommUnityPayConstants.REQUEST_CODE_SUCCESS, CommUnityPayConstants.PAY_METHOD_WECHAT, CommUnityPayConstants.PAY_MEDIUM_APP, entity.getData());
            } else {
                //支付宝充值
                CommUnityPayUtil.goPay(mActivity, CommUnityPayConstants.REQUEST_CODE_SUCCESS, CommUnityPayConstants.PAY_METHOD_ALIPAY_SDK, CommUnityPayConstants.PAY_MEDIUM_APP, entity.getData());

            }
        }


    }

    @Override
    public void setActiveFail(String msg) {
        rechargeTipsRl.setVisibility(View.GONE);
        rechargeActive.setVisibility(View.GONE);
    }

    @Override
    public void rechargeFail(String msg) {
        showNormal("充值失败");

    }

    @SuppressLint("CheckResult")
    private void paymentCallback() {
        toPayRxBusObser = RxBus.getInstance().register(PayEvent.toPayRxBusTag, PayEvent.class);
        toPayRxBusObser.subscribe(payEvent -> {
            //支付成功回调
            int payResult = payEvent.getPayResult();
            if (payResult == CommUnityPayConstants.PAY_RESULT_SUCCESS) {
                handleToPayState(0);
            } else if (payResult == CommUnityPayConstants.PAY_RESULT_CANCEL) {
                handleToPayState(-1);
            } else if (payResult == CommUnityPayConstants.PAY_RESULT_ERROR) {
                handleToPayState(-2);
            }
        });
    }

    /**
     * 处理支付成功状态
     *
     * @param code
     */
    @SuppressLint("CheckResult")
    private void handleToPayState(int code) {
        if (code == CodeType.RECODE_1.getCodeType()) {
            //充值成功
            showNormal("充值成功");
            EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_MONEY_DETAIL));
            RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);
            finish();
        } else {
            //支付未成功
            showNormal(getResources().getString(R.string.fail_pay));
            RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getInstance().unregister(PayEvent.toPayRxBusTag, toPayRxBusObser);

    }

    @OnClick(R2.id.recharge_back)
    public void backClick(View view) {
        QMUIKeyboardHelper.hideKeyboard(rechargeEdit);
        finish();

    }

    @OnClick(R2.id.recharge_edit_delete)
    public void deleteClick(View view) {
        rechargeEdit.setText("");

    }


    @OnClick(R2.id.recharge_wechat_rl)
    public void wechatClick(View view) {
        //微信支付
        if (rechargeType != 1) {
            rechargeWechatChoose.setImageResource(R.mipmap.choose_red_yes);
            rechargeAlipayChoose.setImageResource(R.mipmap.choose_red_no);
            rechargeType = 1;

            sContent = rechargeEdit.getText().toString().trim();
            if (!RxDataTool.isNullString(sContent)) {
                //输入内容不为空
                String last = sContent.substring(sContent.length() - 1);
                if (!last.equals(".")) {
                    //最后一位不是.
                    double rechargeMoney = RxDataTool.stringToDouble(sContent);
                    if (rechargeMoney > 0) {
                        //金额大于0
                        rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_red);
                        rechargeEnter.setEnabled(true);

                    }
                }

            }
        }


    }

    @OnClick(R2.id.recharge_alipay_rl)
    public void alipayClick(View view) {
        //支付宝支付
        if (rechargeType != 2) {
            rechargeAlipayChoose.setImageResource(R.mipmap.choose_red_yes);
            rechargeWechatChoose.setImageResource(R.mipmap.choose_red_no);
            rechargeType = 2;

            sContent = rechargeEdit.getText().toString().trim();
            if (!RxDataTool.isNullString(sContent)) {
                //输入内容不为空
                String last = sContent.substring(sContent.length() - 1);
                if (!last.equals(".")) {
                    //最后一位不是.
                    double rechargeMoney = RxDataTool.stringToDouble(sContent);
                    if (rechargeMoney > 0) {
                        //金额大于0
                        rechargeEnter.setBackgroundResource(R.drawable.border_recharge_enter_red);
                        rechargeEnter.setEnabled(true);

                    }
                }

            }
        }


    }
}
